﻿using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace Kingdee.SR.TD.PulgIn
{
    /// <summary>
    /// 眉山webapi
    /// </summary>
    public class K3CloudWebApiMS
    {
        string K3CloudIP = "";
        string K3CloudDbid = "";
        string K3CloudUserName = "";
        string K3CloudPassword = "";
        private K3CloudApiClient K3Client;

        public bool isLogin = false;

        public K3CloudWebApiMS(string _ip, string _dbid, string _name, string _password)
        {
            K3CloudIP = _ip;
            K3CloudDbid = _dbid;
            K3CloudUserName = _name;
            K3CloudPassword = _password;

            K3Client = K3CloudLogin();
            if (K3Client != null)
            {
                isLogin = true;
            }
        }

        #region 登录K3   
        /// <summary>
        /// 登录K3
        /// </summary>
        /// <returns></returns>
        public K3CloudApiClient K3CloudLogin()
        {
            K3CloudApiClient client = new K3CloudApiClient("http://" + K3CloudIP + "/K3Cloud/");
            var loginResult = client.ValidateLogin(K3CloudDbid, K3CloudUserName, K3CloudPassword, 2052);
            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            DateTime startTime = DateTime.Now;
            //登录结果类型等于1，代表登录成功
            if (resultType == 1 || resultType == 5)
            {

                return client;
            }
            else
            {
                //登录失败返回提示
                //var remsg = JObject.Parse(loginResult)["Message"].Value<string>();
            }
            return null;
        }
        #endregion

        #region 两个时间相差秒
        /// <summary>
        /// 两个时间相差秒
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public double DiffSeconds(DateTime startTime, DateTime endTime)
        {
            TimeSpan secondSpan = new TimeSpan(endTime.Ticks - startTime.Ticks);
            return secondSpan.TotalSeconds;
        }
        #endregion

        #region 查询单据
        /// <summary>
        /// 单据查询
        /// </summary>
        /// <param name="queryJson">单据查询Json</param>
        /// <returns>返回list</returns>
        public List<List<object>> BillQuery(string queryJson)
        {
            return K3Client.ExecuteBillQuery(queryJson);
        }
        #endregion

        #region 单据查看
        /// <summary>
        /// 单据查看
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="viewJson">查看单据Json</param>
        /// <returns>返回list</returns>
        public string BillView(string formId, string viewJson)
        {
            return K3Client.View(formId, viewJson);
        }
        #endregion

        #region 单据下推
        /// <summary>
        /// 单据下推
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">下推json</param>
        /// <returns>返回字符串</returns>
        public string PushBill(string formId, string json)
        {
            return K3Client.Push(formId, json);
        }
        #endregion

        #region 保存单据
        /// <summary>
        /// 保存单据
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">保存单据json</param>
        /// <returns>返回字符串</returns>
        public string SaveBill(string formId, string json)
        {
            return K3Client.Save(formId, json);
        }
        #endregion

        #region 删除单据
        /// <summary>
        /// 保存单据
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">删除单据json</param>
        /// <returns>返回字符串</returns>
        public string DeleteBill(string formId, string json)
        {
            return K3Client.Delete(formId, json);
        }
        #endregion

        #region 提交
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">分配json"{"PkIds": "452623","TOrgIds": "100041","IsAutoSubmitAndAudit":"true"}"</param>
        /// <returns>返回字符串</returns>
        public string Submit(string formId, string json)
        {
            return K3Client.Submit(formId, json);
        }
        #endregion

        #region 撤销
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">撤销json""PUR_PurchaseOrder","{"CreateOrgId":0,"Numbers":[],"Ids":"","NetworkCtrl":""}");"</param>
        /// <returns>返回字符串</returns>
        public string CancelAssign(string formId, string json)
        {
            return K3Client.CancelAssign(formId, json);
        }
        #endregion

        #region 审核
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">分配json"{"PkIds": "452623","TOrgIds": "100041","IsAutoSubmitAndAudit":"true"}"</param>
        /// <returns>返回字符串</returns>
        public string Audit(string formId, string json)
        {
            return K3Client.Audit(formId, json);
        }
        #endregion

        #region 工作流审核
        /// <summary>
        /// 工作流审核
        /// </summary>
        /// <param name="json">client.WorkflowAudit("{"FormId":"","Ids":[],"Numbers":[],"UserId":0,"UserName":"","ApprovalType":0,"ActionResultId":"","PostId":0,"PostNumber":"","Disposition":""}");</param>
        /// <returns>返回字符串</returns>
        public string WorkflowAudit(string json)
        {
            return K3Client.WorkflowAudit(json);
        }
        #endregion

        #region 反审核
        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">json"{"CreateOrgId": 0,"Numbers": [],"Ids": "","InterationFlags": "","IgnoreInterationFlag": "","NetworkCtrl": "","IsVerifyProcInst": ""}"</param>
        /// <returns>返回字符串</returns>
        public string UnAudit(string formId, string json)
        {
            return K3Client.UnAudit(formId, json);
        }
        #endregion

        #region 分配
        /// <summary>
        /// 分配
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">分配json"{"PkIds": "452623","TOrgIds": "100041","IsAutoSubmitAndAudit":"true"}"</param>
        /// <returns>返回字符串</returns>
        public string Allocate(string formId, string json)
        {
            return K3Client.Allocate(formId, json);
        }
        #endregion

        #region 销售订单单个保存   
        /// <summary>
        /// 销售订单单个保存
        /// </summary>
        /// <param name="orderJson">销售订单json集合</param>
        /// <returns></returns>
        public string SaveSaleOrder(string orderJson)
        {
            K3CloudApiClient client = new K3CloudApiClient("http://" + K3CloudIP + "/K3Cloud/");
            var loginResult = client.ValidateLogin(K3CloudDbid, K3CloudUserName, K3CloudPassword, 2052);
            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            string sql = "";
            DateTime startTime = DateTime.Now;
            //登录结果类型等于1，代表登录成功
            if (resultType == 1 || resultType == 5)
            {
                //保存销售订单
                string json = "{\"IsAutoAdjustField\":" + orderJson + ",\"Model\":" + orderJson + "}";
                string result = client.Save("SAL_SaleOrder", json);
                //NLogHelper.Nlogger.Trace("Post:" + json + "|Result:" + result);
                var resultType1 = JObject.Parse(result);
                if (!JObject.Parse(result)["Result"]["ResponseStatus"]["IsSuccess"].Value<bool>())
                {
                    //失败
                    //NLogHelper.Nlogger.Info("Post:" + json + "|Result:" + result);

                }
                else
                {
                    //成功
                    //NLogHelper.Nlogger.Trace("Post:" + json + "|Result:" + result);
                }
                return result;
            }
            //登录失败返回提示
            var remsg = JObject.Parse(loginResult)["Message"].Value<string>();
            //NLogHelper.Nlogger.Info("Post:登录金蝶失败|Result:" + loginResult);
            return remsg;
        }
        #endregion

        #region 查询报表数据
        /// <summary>
        /// 查询报表数据
        /// </summary>
        /// <param name="formId">单据id</param>
        /// <param name="json">分配json"{"PkIds": "452623","TOrgIds": "100041","IsAutoSubmitAndAudit":"true"}"</param>
        /// <returns>返回字符串</returns>
        public string GetSysReportData(string formId, string json)
        {
            return K3Client.GetSysReportData(formId, json);
        }
        #endregion

        #region 发送消息
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="json">"{\"Model\":[{\"FTitle\":\"我是标题\",\"FContent\":\"我是内容\",\"FReceivers\":\"demo\",\"FType\":\"1\"}]}"</param>
        /// <returns>返回字符串</returns>
        public string SendMessage(string json)
        {
            return K3Client.SendMsg(json);
        }
        #endregion

        #region 切换组织
        /// <summary>
        /// 切换组织
        /// </summary>
        /// <param name="OrgNumber">组织编码</param>
        /// <returns>返回list</returns>
        public string SwitchOrg(string OrgNumber)
        {
            return K3Client.SwitchOrg(OrgNumber);
        }
        #endregion

    }
}
